<template>
  <div class="fg-code">
    <pre :id="id" v-highlight v-if="!loading"><code>{{code}}</code></pre>
    <el-button type="text" @click="handleCopy">{{isCopy?'已复制':'复制'}}</el-button>
  </div>
</template>

<script>
import "highlight.js/styles/atom-one-dark.css"; // 黑色主题
// import "highlight.js/styles/atom-one-light.css";
import hljs from "highlight.js/lib/core";
// 仅包含你需要的语言
import javascript from "highlight.js/lib/languages/javascript";
import xml from "highlight.js/lib/languages/xml";
// 注册语言
hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("xml", xml);

export default {
  props: {
    code: {
      default: ""
    }
  },
  data() {
    return {
      loading: false,
      isCopy: false,
      id: new Date().getTime().toString()
    };
  },
  watch: {
    code() {
      this.loading = true;
      this.$nextTick(() => {
        this.loading = false;
      });
    }
  },
  methods: {
    handleCopy() {
      if (this.isCopy) return;
      const codeSnippet = document.getElementById(this.id);
      const selection = window.getSelection();
      const range = document.createRange();
      // 选中需要复制的代码
      range.selectNodeContents(codeSnippet);
      selection.removeAllRanges();
      selection.addRange(range);

      // 复制到剪贴板
      const successful = document.execCommand("copy");
      if (successful) {
        // this.$message.success("代码复制成功");
        this.isCopy = true;
        setTimeout(() => {
          this.isCopy = false;
          clearTimeout();
        }, 3000);
      } else {
        this.$message.error("代码复制失败");
      }

      // 清除选区
      window.getSelection().removeAllRanges();
    }
  },
  directives: {
    highlight: el => {
      let blocks = el.querySelectorAll("pre code");
      blocks.forEach(block => {
        hljs.highlightBlock(block);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.fg-code {
  position: relative;
  pre {
    margin: 0;
    width: 100%;
    overflow-x: auto;
    border-radius: 8px;
  }
  code {
    font-size: 16px;
    font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  }
  .el-button {
    position: absolute;
    top: 0;
    right: 12px;
  }
}
</style>
